import {getRequest} from "../utils/MyRequest.js";
import axios from "axios";
import {BASE_URL} from "../config/index.js";

/**
 * 获取服务器文件列表
 */
export async function getFileListApi(page,size,type=-1) {
    return await getRequest(`/files/list?page=${page}&size=${size}&type=${type}`)
}

/**
 * 删除文件，根据文件名
 * @param fileName
 */
export async function deleteFileApi(fileName) {
    return await getRequest("/files/delete?fileName=" + fileName)
}

/**
 * 清空所有xlsx文件
 * files/clear/xlsx
 */
export async function clearXlsxFileApi() {
    return await getRequest("/files/clear/xlsx")
}

/**
 * 下载文件
 */
export async function downloadFileApi(fileName) {
    const response =  await axios.get(BASE_URL + "/files/download?fileName=" + fileName,{
        responseType: 'blob',
        transformResponse: [data => data], // 禁止自动转换
        withCredentials:true
    })
    // 解析 Content-Disposition
    const contentDisposition = response.headers['content-disposition'];

    if (contentDisposition) {
        // 尝试解析 filename*=UTF-8'' 格式
        const utf8FilenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)/);
        if (utf8FilenameMatch) {
            fileName = decodeURIComponent(utf8FilenameMatch[1]);
        } else {
            // 尝试解析 filename="..." 格式
            const filenameMatch = contentDisposition.match(/filename="(.+)"/);
            if (filenameMatch) fileName = filenameMatch[1];
        }
    }

    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    link.remove();
}